'''
The configuration file reader

Created on 2013-5-25

@author: Soul
'''

from IpRoute import *
param_map = {}

class Configurator():
    def __init__(self, filename):
        if filename:  # should add some validations here
            self.__filename__ = filename
            self._read_()
            self._load_route_()
        else:
            return None
    
    def _read_(self):
        global param_map
        config_file = open(self.__filename__)
        lines = config_file.readlines()
        for line in lines:
            if line and line.strip() and (not line[0] == '#'):
                key = "".join((line.split('='))[0])
                val = "".join((line.split('='))[1])
                param_map[key.strip()] = val.strip()
        config_file.close()

    def _load_route_(self):
        self._router_conf_ = IpRouter(param_map['route_file'])
    
    @staticmethod
    def get_val(key):
        global param_map
        if param_map.has_key(key):
            return param_map[key]
        else:
            return None

    @staticmethod
    def get_template(website_dmoain, website_name):
        global route_map_array
        ip = IpRouter.getIp(website_dmoain)
        for route_item in route_map_array:
            import re
            if re.search(route_item['ip_pattern'], ip) != None:
                keywds = route_item['website_keywords']
                for kw in keywds:
                    if website_dmoain.find(kw) != -1 or website_name.find(kw) != -1:
                        return route_item['website_tpl']
        return ''